import { HeadObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
import { System } from "./System";

export async function uploadFileToS3(system: System, key: string, file: File) {
  const bucket = system.bucket;
  const endpointUrl = system.endpoint;
  // 先检查文件是否存在
  try {
    const headCommand = new HeadObjectCommand({
      Bucket: bucket,
      Key: key,
    });
    await system.s3Client.send(headCommand);
    return {
      success: false,
      url: `${endpointUrl}/${bucket}/${key}`,
    };
  } catch (error) {
    // 文件不存在，继续上传
    const params = {
      Bucket: bucket,
      Key: key,
      Body: new Uint8Array(await file.arrayBuffer()),
      ContentType: file.type,
    };
    try {
      const command = new PutObjectCommand(params);
      await system.s3Client.send(command);
      return {
        success: true,
        url: `${endpointUrl}/${bucket}/${key}`,
      };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : "Unknown error",
      };
    }
  }
}
